package by.amakarevich.dataaccess.Impl;

import java.util.List;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Repository;

import by.amakarevich.dataaccess.ThreadDao;
import by.amakarevich.datamodel.Product;
import by.amakarevich.datamodel.Thread;
import by.amakarevich.datamodel.Thread_;

@Repository
public class ThreadDaoImpl extends AbstractDaoImpl<Long, Thread> implements ThreadDao{
	protected ThreadDaoImpl(){
		super(Thread.class);
	}
	
	@Override
	public List<Thread> getAllThread(){
        CriteriaBuilder cBuilder = getEm().getCriteriaBuilder();

        CriteriaQuery<Thread> criteria = cBuilder.createQuery(Thread.class);
        Root<Thread> root = criteria.from(Thread.class);

        criteria.select(root);
        root.fetch(Thread_.product);
        criteria.distinct(true);
        

        TypedQuery<Thread> query = getEm().createQuery(criteria);
        List<Thread> results = query.getResultList();
        return results;
	}
	 
	public Thread getByProductId(Product product){
		  CriteriaBuilder cBuilder= getEm().getCriteriaBuilder();
		  CriteriaQuery<Thread> criteria=cBuilder.createQuery(Thread.class);
		  Root<Thread> root=criteria.from(Thread.class);
		  
		  criteria.select(root);
	      root.fetch(Thread_.product);
	      criteria.distinct(true);
		  criteria.where(cBuilder.equal(root.get(Thread_.product),product.getId()));

		  TypedQuery<Thread> query = getEm().createQuery(criteria);
		  Thread results = (Thread)query.getSingleResult();
	      return results;
	}
}
